<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" icon="Edit" @click="handleUpdate"
            v-hasPermi="['patients:patients:list', 'patients:patients:edit']">修改信息</el-button>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="id">{{ form.id }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ form.user }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <dict-tag :options="sys_user_sex" :value="form.gender" />
        </el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ parseTime(form.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ form.phone }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">药品冲突信息</el-divider>
      <el-table :data="form.conflictList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品名称" prop="medicationId" align="center">
          <template #default="scope">
            {{ getMedicationName(scope.row.medicationId) }}
          </template>
        </el-table-column>
        <el-table-column label="基本症状" prop="symptom" align="center" />
      </el-table>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>处方信息</span>
        </div>
      </template>
      <el-table v-loading="loading" :data="prescriptionList" role="grid" aria-label="处方列表">
        <el-table-column label="处方ID" align="center" prop="id" />
        <el-table-column label="医护人员" align="center" prop="employeeId">
          <template #default="scope">
            {{ getEmployeeName(scope.row.employeeId) }}
          </template>
        </el-table-column>
        <el-table-column label="处方状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_prescription_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="开据时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleViewPrescription(scope.row)"
              v-hasPermi="['prescription:prescription:list']">查看</el-button>
            <el-button v-if="scope.row.status === '2'" link type="success" icon="Check"
              @click="handleStatusChange(scope.row, '3')" v-hasPermi="['patients:patients:list']">完成</el-button>
            <el-button v-if="scope.row.status === '2'" link type="danger" icon="Close"
              @click="handleStatusChange(scope.row, '4')" v-hasPermi="['patients:patients:list']">失败</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改患者对话框 -->
    <el-dialog title="修改个人信息" v-model="open" width="500px" append-to-body>
      <el-form ref="patientsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="user">
          <el-input v-model="form.user" placeholder="请输入用户名" disabled />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable v-model="form.birthDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择出生日期" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别，1 男，2 女">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-divider content-position="center">药品冲突信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddConflict">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteConflict">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="conflictList" :row-class-name="rowConflictIndex"
          @selection-change="handleConflictSelectionChange" ref="conflict">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="药品id" prop="medicationId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.medicationId" placeholder="请输入药品id" />
            </template>
          </el-table-column>
          <el-table-column label="基本症状" prop="symptom" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.symptom" placeholder="请输入基本症状" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看处方对话框 -->
    <el-dialog title="处方详情" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="处方ID">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="医护人员">{{ getEmployeeName(viewForm.employeeId) }}</el-descriptions-item>
        <el-descriptions-item label="处方状态">
          <dict-tag :options="sys_prescription_status" :value="viewForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="开据时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">处方药品信息</el-divider>
      <el-table :data="viewForm.prescriptionDetailList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="处方序号" prop="prescriptionId" align="center" />
        <el-table-column label="药品名称" prop="medicationId" align="center">
          <template #default="scope">
            {{ getMedicationName(scope.row.medicationId) }}
          </template>
        </el-table-column>
        <el-table-column label="用法用量" prop="dosage" align="center" />
        <el-table-column label="单价" prop="price" align="center" />
        <el-table-column label="数量" prop="quantity" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Patients">
import {
  listPatients,
  getPatients,
  delPatients,
  addPatients,
  updatePatients,
} from "@/api/patients/patients";
import { getInfo } from "@/api/login";
import {
  listPrescription,
  getPrescription,
  delPrescription,
  addPrescription,
  updatePrescription,
} from "@/api/prescription/prescription";
import { listMedication } from "@/api/medication/medication";
import { listEmployee } from "@/api/employee/employee";

const { proxy } = getCurrentInstance();
const { sys_user_sex, sys_prescription_status } = proxy.useDict("sys_user_sex", "sys_prescription_status");
const form = ref({});
const conflictList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const checkedConflict = ref([]);
const prescriptionList = ref([]);
const viewForm = ref({
  id: undefined,
  employeeId: undefined,
  status: undefined,
  createTime: undefined,
  prescriptionDetailList: []
});

// 药品和医护人员数据
const medicationList = ref([]);
const employeeList = ref([]);

// 获取药品列表
function getMedicationList() {
  listMedication().then(response => {
    medicationList.value = response.rows;
  });
}

// 获取医护人员列表
function getEmployeeList() {
  listEmployee().then(response => {
    employeeList.value = response.rows;
  });
}

// 根据ID获取药品名称
function getMedicationName(id) {
  const medication = medicationList.value.find(item => item.id === id);
  return medication ? medication.name : id;
}

// 根据ID获取医护人员姓名
function getEmployeeName(id) {
  const employee = employeeList.value.find(item => item.id === id);
  return employee ? employee.name : id;
}

// 在组件挂载时获取数据
onMounted(() => {
  getMedicationList();
  getEmployeeList();
  getCurrentUserInfo();
});

const data = reactive({
  rules: {
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    birthDate: [
      { required: true, message: "出生日期不能为空", trigger: "blur" },
    ],
    phone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
    gender: [
      {
        required: true,
        message: "性别，1 男，2 女不能为空",
        trigger: "change",
      },
    ],
  },
});

const { rules } = toRefs(data);

/** 获取当前用户信息 */
function getCurrentUserInfo() {
  loading.value = true;
  getInfo().then(response => {
    const username = response.user.userName;
    // 根据用户名查询患者信息
    listPatients({ user: username }).then(res => {
      if (res.rows && res.rows.length > 0) {
        form.value = res.rows[0];
        conflictList.value = res.rows[0].conflictList || [];
        // 根据患者ID查询处方信息
        getPrescriptionList(res.rows[0].id);
      }
      loading.value = false;
    });
  });
}

/** 获取处方列表 */
function getPrescriptionList(patientsId) {
  loading.value = true;
  listPrescription({ patientsId: patientsId }).then(response => {
    prescriptionList.value = response.rows;
    console.log('处方列表:', response.rows); // 添加日志
    loading.value = false;
  });
}

/** 查看处方详情 */
function handleViewPrescription(row) {
  getPrescription(row.id).then(response => {
    viewForm.value = response.data;
    // 确保 medicationList 是数组
    if (!viewForm.value.medicationList) {
      viewForm.value.medicationList = [];
    }
    viewOpen.value = true;
  }).catch(error => {
    console.error('获取处方信息失败:', error);
    proxy.$modal.msgError("获取处方信息失败");
  });
}

/** 状态切换操作 */
function handleStatusChange(row, status) {
  console.log('当前处方状态:', row.status); // 添加日志
  const statusText = status === '3' ? '完成' : '失败';
  proxy.$modal.confirm('是否确认将处方状态修改为"' + statusText + '"？').then(() => {
    const prescription = {
      id: row.id,
      status: status
    };
    return updatePrescription(prescription);
  }).then(() => {
    getPrescriptionList(form.value.id);
    proxy.$modal.msgSuccess("状态修改成功");
  }).catch(() => { });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  conflictList.value = form.value.conflictList || [];
  proxy.resetForm("patientsRef");
}

/** 修改按钮操作 */
function handleUpdate() {
  reset();
  open.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patientsRef"].validate((valid) => {
    if (valid) {
      form.value.conflictList = conflictList.value;
      updatePatients(form.value).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getCurrentUserInfo();
      });
    }
  });
}

/** 药品冲突序号 */
function rowConflictIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 药品冲突添加按钮操作 */
function handleAddConflict() {
  let obj = {};
  obj.medicationId = "";
  obj.symptom = "";
  conflictList.value.push(obj);
}

/** 药品冲突删除按钮操作 */
function handleDeleteConflict() {
  if (checkedConflict.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的药品冲突数据");
  } else {
    const conflicts = conflictList.value;
    const checkedConflicts = checkedConflict.value;
    conflictList.value = conflicts.filter(function (item) {
      return checkedConflicts.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleConflictSelectionChange(selection) {
  checkedConflict.value = selection.map((item) => item.index);
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>
